package elearning.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import elearning.model.CmsUser;


@Repository
public class CmsUserDao {

	@PersistenceContext
	private EntityManager em;
	
	@Transactional
	public List<CmsUser> queryAll() {
        Query query = em.createQuery("SELECT t FROM CmsUser t");
        List<CmsUser> result = (List<CmsUser>)query.getResultList();
        return result;
    }
	@Transactional
    public CmsUser get(Integer id){
        return em.find(CmsUser.class,id);
    }
	@Transactional
    public CmsUser getByUserName(String userName){
		Query query = em.createQuery("SELECT t FROM CmsUser t where t.userName=?1");
        query.setParameter(1, userName);
        List result = query.getResultList();
        if(result.isEmpty()){
        	return null;
        }
       	return (CmsUser)result.get(0);
    }
	@Transactional
    public CmsUser save(CmsUser cmsUser){
        try {
			em.persist(cmsUser);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return cmsUser;
    }
	@Transactional
    public CmsUser update(CmsUser cmsUser){
    	cmsUser = em.merge(cmsUser);
        return cmsUser;
    }
}
